﻿using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Web;
using DBScript;
using eBlog.Common;
using eBlog.Common.Files;
using eBlog.Entity;
using System.Web.UI;
using eBlog.Service;

namespace eBlog.Core
{
    /// <summary>
    /// 系统基类
    /// </summary>
    public class PageBase : Page
    {

        private string _action = "list"; //初始化页面状态
        private int _id = 0;
        private int _pageSize = 20;
        private int _listCount = 0;
        /// <summary>
        /// 主题名称(文件夹)
        /// </summary>
        public string ThemeName;
        #region ==========基本属性
        /// <summary>
        /// 当前url参数
        /// </summary>
        public string action
        {
            get { return _action; }
            set { _action = value; }
        }
        
        /// <summary>
        /// 当前ID
        /// </summary>
        public int id
        {
            get { return _id; }
            set { _id = value; }
        }
        
        /// <summary>
        /// 设置页面大小
        /// </summary>
        public int PageSize
        {
            get { return _pageSize; }
            set { _pageSize = value; }
        }

        
        /// <summary>
        /// 列表内容记录总数
        /// </summary>
        public int ListCount
        {
            get { return _listCount; }
            set { _listCount = value; }
        }


        #endregion 

        public string AppRootPath = ((HttpContext.Current.Request.ApplicationPath == "/") ? "" : HttpContext.Current.Request.ApplicationPath);
        public string WebRootPath = HttpContext.Current.Request.PhysicalApplicationPath.Substring(0, HttpContext.Current.Request.PhysicalApplicationPath.Length - 1);
        protected string ConfigPath = "/config/";


        private string _templateUrl;
        public NVelocityHelper dict;   //模板引擎

        protected void Page_Init(object sender, EventArgs e)
        {
            //页面初始化

           // themeName = SettingService.GetSetting().Theme;//获取主题名称
            ThemeName = SettingService.GetSetting().Theme; ;//获取主题名称

            if (!String.IsNullOrEmpty(Request.QueryString["id"]) && PageValidate.IsNumber(Request.QueryString["id"]))
            {
                id = int.Parse(Request.QueryString["id"]);
            }

            if (Request.QueryString["action"] != null && Request.QueryString["action"].Trim() != "")
            {
                action = Request.QueryString["action"].ToLower().Trim();
            }

        }
        #region 加载全局标签
        /// <summary>
        /// 加载全局标签
        /// </summary>
        private void LoadGlobalTagFields()
        {
            #region 全局

            dict.Put(TagFields.SITE_NAME, SettingService.GetSetting().SiteName);
            dict.Put(TagFields.SITE_DESCRIPTION, SettingService.GetSetting().SiteDescription);
            dict.Put(TagFields.META_KEYWORDS, SettingService.GetSetting().MetaKeywords);
            dict.Put(TagFields.META_DESCRIPTION, SettingService.GetSetting().MetaDescription);

            dict.Put(TagFields.FOOTER_HTML, SettingService.GetSetting().FooterHtml);

            dict.Put(TagFields.VERSION, SettingService.GetSetting().Version);

            dict.Put(TagFields.PAGE_TITLE, "首页");

            dict.Put(TagFields.SITE_PATH, ConfigHelper.SitePath);
            dict.Put(TagFields.SITE_URL, ConfigHelper.SiteUrl);
            
#pragma warning disable 612,618
            dict.Put(TagFields.THEME_PATH, ConfigHelper.SitePath + "themes/" + ThemeName + "/");
#pragma warning restore 612,618

            dict.Put(TagFields.THEME_URL, ConfigHelper.SiteUrl + "themes/" + ThemeName + "/");

            dict.Put(TagFields.IS_DEFAULT, "0");
            
            dict.Put(TagFields.IS_POST, "0");

            dict.Put(TagFields.FEED_URL, ConfigHelper.SiteUrl + "feed/post" + SettingService.GetSetting().RewriteExtension);
            dict.Put(TagFields.FEED_COMMENT_URL, ConfigHelper.SiteUrl + "feed/comment" + SettingService.GetSetting().RewriteExtension);

            dict.Put(TagFields.PAGER, string.Empty);
            dict.Put(TagFields.PAGER_INDEX, RequestHelper.QueryInt("page", 1));

           // dict.Put(TagFields.URL, CurrentUrl);
            dict.Put(TagFields.DATE, DateTime.Now);

            dict.Put(TagFields.ARCHIVES, ArchiveService.GetArchive());

            dict.Put(TagFields.SEARCH_KEYWORD, string.Empty);

            dict.Put(TagFields.QUERY_COUNT, 0);
            dict.Put(TagFields.PROCESS_TIME, 0);

            dict.Put(TagFields.ENABLE_VERIFYCODE, SettingService.GetSetting().EnableVerifyCode);

            string headhtml = string.Empty;

            headhtml += string.Format("<meta name=\"generator\" content=\"Loachs {0}\" />\n", SettingService.GetSetting().Version);
            headhtml += "<meta name=\"author\" content=\"Loachs Team\" />\n";
            headhtml += string.Format("<meta name=\"copyright\" content=\"2008-{0} Loachs Team.\" />\n", DateTime.Now.Year);
            headhtml += string.Format("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"{0}\"  href=\"{1}\"  />\n", SettingService.GetSetting().SiteName, ConfigHelper.SiteUrl + "feed/post" + SettingService.GetSetting().RewriteExtension);
            headhtml += string.Format("<link rel=\"EditURI\" type=\"application/rsd+xml\" title=\"RSD\" href=\"{0}xmlrpc/rsd.aspx\" />\n", ConfigHelper.SiteUrl);
            headhtml += string.Format("<link rel=\"wlwmanifest\" type=\"application/wlwmanifest+xml\" href=\"{0}xmlrpc/wlwmanifest.aspx\" />", ConfigHelper.SiteUrl);

            dict.Put(TagFields.HEAD, headhtml);

            #endregion
        }

        private void LoadDefault()
        {
            #region 作者,分类,标签,最近评论

            dict.Put(TagFields.RECENT_COMMENTS, CommentService.GetCommentListByRecent(SettingService.GetSetting().SidebarCommentCount));
            dict.Put(TagFields.AUTHORS, UserService.GetUserList());
            dict.Put(TagFields.CATEGORIES, TermsService.GetPostsTypeList());
            dict.Put(TagFields.RECENT_TAGS, TermsService.GetPostsTagsList(SettingService.GetSetting().SidebarTagCount));

            #endregion

            #region 连接

            dict.Put(TagFields.LINKS, LinksService.GetLinkList(-1, 1));
            dict.Put(TagFields.NAV_LINKS, LinksService.GetLinkList((int)LinkPosition.Navigation, 1));
            dict.Put(TagFields.GENERAL_LINKS, LinksService.GetLinkList((int)LinkPosition.General, 1));

            #endregion

            #region 统计
            dict.Put(TagFields.POST_COUNT, StatisticsService.GetStatistics().PostCount);
            dict.Put(TagFields.COMMENT_COUNT, StatisticsService.GetStatistics().CommentCount);
            dict.Put(TagFields.VIEW_COUNT, StatisticsService.GetStatistics().VisitCount);
            dict.Put(TagFields.AUTHOR_COUNT, UserService.GetUserList().Count);
            dict.Put(TagFields.USER_COUNT, UserService.GetUserList().Count);
            #endregion
        }

        #endregion

        #region ==========模板引擎接口方法======
        /// <summary>
        /// 使用模板时,必须进行初始化
        /// </summary>
        protected void Init_Template()
        {
            string templatePath = Server.MapPath(string.Format("/themes/{0}/template/", ThemeName));
            dict = NVelocityHelper.getNVE("themes/" + ThemeName + "/template");
            dict.Add("WebRoot", "/");
            dict.Put("now", DateTime.Now);
            dict.Put("this", this);
            dict.Put("base", new BaseCode());//全局函数
            LoadGlobalTagFields();//加载全局标签
            LoadDefault();
        }
        public string Current(string urlParam)
        {
            if (action == urlParam)
                return "current";

            return "";
        }
        /// <summary>
        /// 每个模板页需要先对该属性时行赋值。如inculde/listPage.htm
        /// </summary>
        public string TemplateUrl
        {
            get
            {
                return _templateUrl;
            }
            set
            {
                _templateUrl = value;
            }
        }

        protected void WriteHTML()
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(dict.GetStringFromVm(this.TemplateUrl).ToString());
            //HttpContext.Current.Response.Flush();
        }

        protected string GetHTML()
        {
            return dict.GetStringFromVm(this.TemplateUrl).ToString();
        }

        protected string GetHTMLFromString(string source_Code)
        {
            return dict.GetStringFromSource(source_Code).ToString();
        }

        #endregion
    }
}
